package org.yimon.tool.algo.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ym.gao
 * @Description 二叉树的后序遍历 左节点->右节点->根节点
 * @Date 2024/8/20 下午3:39
 */
public class LeetCode_145_PostorderTraversal {

    public static void main(String[] args) {
        System.out.println(LeetCode_145_PostorderTraversal.preorderTraversal(new TreeNode(1, null, new TreeNode(2, new TreeNode(3), null))));
    }

    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        //特殊情况判断
        if (root == null) {
            return result;
        }
        preorder(root, result);
        return result;
    }

    private static void preorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        //后序遍历先书顺序：左节点->右节点->根节点
        preorder(root.left, res);//左节点
        preorder(root.right, res);//右节点
        res.add(root.val);//根节点
    }

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
